package io.renren.modules.person.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.renren.common.exception.RRException;
import io.renren.common.utils.R;
import io.renren.modules.person.mapper.PersonMapper;
import io.renren.modules.person.model.Person;
import io.renren.modules.person.service.PersonService;
import io.renren.modules.shop.mapper.ShopManageMapper;
import io.renren.modules.shop.model.ShopManage;
import io.renren.modules.shop.service.ShopManageService;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author A夜兔A
 * @data 2021年11月16日 17:36
 */
@Service
public class PersonServiceImpl implements PersonService {

    @Autowired
    private PersonMapper personMapper;

    @Autowired
    private ShopManageService shopManageService;

    @Override
    public R getVIP(Integer pageNum, Integer pageSize, String keyword) {

        SysUserEntity userEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();

        boolean flag = shopManageService.isAdmin();

        long userId=0L;
        ShopManage shopManage=null;
        if (!flag){
            userId=userEntity.getUserId();
             shopManage = shopManageService.getOne(new LambdaQueryWrapper<ShopManage>()
                    .eq(ShopManage::getUserId, userEntity.getCreateUserId()));

        }else {
             shopManage = shopManageService.getOne(new LambdaQueryWrapper<ShopManage>()
                    .eq(ShopManage::getUserId, userEntity.getUserId()));
        }

        String tableName=shopManage.getShopNum()+"_customers";

        Page<Person> page =new Page<>(pageNum,pageSize);

        Page<Person> personList=personMapper.getVIP(page,keyword,tableName,userId);

        return R.ok("操作成功").put("personList",personList);

    }

    @Override
    public R addVIP(Person person) {

        String tableName=person.getShopNum()+"_customers";
        try {
            int count=personMapper.addVIP(tableName,person);
        }catch (DuplicateKeyException d){
            throw new RRException("用户账号重复");
        }

        return R.ok("操作成功");
    }

    @Override
    public R updateVIP(Person person) {

        String tableName=person.getShopNum()+"_customers";
        try {
            int count=personMapper.updateVIP(tableName,person);
        }catch (DuplicateKeyException d){
            throw new RRException("用户账号重复");
        }

        return R.ok("操作成功");


    }

    @Override
    public R delVIP(Person person) {

        String tableName=person.getShopNum()+"_customers";
        int count=personMapper.delVIP(tableName,person.getCustomerId());

        return R.ok("操作成功");
    }
}
